import React, { useEffect, useState, useRef } from "react";
import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import useColumns from "./cloumns";
import Actions from "./components/Actions";
import { getGoodsSpuPage, getGoodsSkuPage, getSkuNotMatchNum, getSpuNotMatchNum } from "./service";
import useOperate from "./useOperate";
import { useSearchParams, useLocation } from "react-router-dom";
import { cloneDeep } from "lodash";
import { getSearchParamsObj } from "@/utils/utils.jsx";

const SystemGoodsPage = () => {
	const fn = useRef(null);
	const btnOperateData = useOperate(fn);
	const { handle } = btnOperateData;
	const [formData, setFormData] = useState({});
	handle.refresh = () => {
		fetchList(query);
	};
	const RefOriginalData = useRef({});
	const RefDataList = useRef();
	const { isSkuType, setIsSkuType, tabValue, setTabValue, columns, setColumns, defaultColumns, skuColumns, spuColumns } =
		useColumns({
			handle,
			...btnOperateData,
			handleEditRow,
			RefDataList,
			RefOriginalData
		});
	// 接口
	const tableRequest = isSkuType ? getGoodsSkuPage : getGoodsSpuPage;
	const tableKey = isSkuType ? "GoodsManageSystemTable_SKU" : "GoodsManageSystemTable_SPU";

	// 待匹配商品数量
	const [notMatchNum, setNotMatchNum] = useState(0);
	// https://ali-react-table.js.org/docs/table/api/

	const {
		selectedKeys,
		selectedRows,
		fetchList,
		dataSource,
		form,
		query,
		pagination,
		updateDataSource,
		updateSearchQuery,
		updatePaginationParams,
		searchSimpleTableProps
	} = useTableConfig({
		tableKey,
		rowKey: "id",
		//
		columns,
		tableRequest,
		autoFetch: true,
		hasPagination: true,
		hasQuickSearch: true,
		beforeQuerySearch: ({ API_DATA }) => {
			RefOriginalData.current = {};
			getNotMatchNum(isSkuType);
			// 1：单品 2：组合
			if (isSkuType) API_DATA.type = 1;
			// 是否匹配全部不传参数
			console.log(API_DATA, 'ddddddddddddddddddddddddd')
			setFormData({ ...API_DATA });
			return { ...API_DATA };
		},
		resetSourceData: false,
		hasColsSetting: true,
		hasToggleSearchForm: true,
		columnResize: true,
        pageSize: 50
	});

	useEffect(() => {
		fn.current = () => {
			fetchList(query);
		};
	}, [isSkuType, query]);

	async function getNotMatchNum(isSkuType) {
		const res = isSkuType ? await getSkuNotMatchNum() : await getSpuNotMatchNum();
		const { data, success } = res;
		if (success) setNotMatchNum(data);
	}

	useEffect(() => {
		getNotMatchNum(isSkuType);
	}, []);

	// 带上query参数的自动请求
	const [searchParams] = useSearchParams();
	const location = useLocation();
	useEffect(() => {
		const urlParams = getSearchParamsObj(location.search);
		const skuCode = urlParams.skuCode || "";
		const ids = urlParams.ids || "";

		const formData = form.getFieldsValue();
		updateSearchQuery(formData);
		if (location.pathname.includes("/views/goods/system") && (skuCode != "" || ids != "")) {
			// 延迟执行，否则form.getFieldsValue()获取到的值有延迟
			form.resetFields();
			setTimeout(() => {
				const searchQuery = skuCode ? { skuCode } : {};
				form.setFieldsValue(searchQuery);
				fetchList(isSkuType ? { ...formData, ...searchQuery, ids: ids ?? -1 } : formData);
			}, 1);
		}
	}, [location.pathname, isSkuType]);

	/**
	 * 处理行编辑操作。
	 * @param {Object} e 事件对象。
	 * @param {Object} data 当前行的编辑数据。
	 * @param {number} rowIndex 当前行的索引。
	 * @param {Object} originalData 原始数据对象，包含列表和原始数据。
	 * 此函数用于处理表格行的编辑操作，包括点击和失去焦点时的行为。
	 * 当点击行时，标记该行为编辑状态，并复制原始数据以供后续比较。
	 * 当失去焦点时，比较编辑后的数据和原始数据，如果有变化则更新数据源。
	 */
	async function handleEditRow(e, data = {}, rowIndex, { list, originalData }) {
		e.stopPropagation();
		// console.log("e", e);
		// console.log(list, originalData);
		const { type } = e;
		if (type === "focus" || !originalData) return;
		const lastIndex = list?.findIndex(e => e.isEdit);
		console.log(lastIndex);
		if (type === "click") {
			if ((JSON.stringify(RefOriginalData.current) !== "{}" && lastIndex != rowIndex) || lastIndex == -1) {
				// console.log("判断数据是否符合保存条件");
				const obj = list[lastIndex];
				// 判断是否可以修改数据
				if ((obj && handle.checkEditRow(obj)) || lastIndex == -1) {
					RefOriginalData.current = cloneDeep(list[rowIndex]);
					editRow(rowIndex);
				}
			}
		}
		// 离开保存数据,
		if (type === "blur") {
			// 判断和原数据是否发生变化
			const changeData = {
				...cloneDeep(list[rowIndex]),
				...data
			};
			if (Object.keys(data).length > 0 && JSON.stringify({ ...originalData, isEdit: true }) != JSON.stringify(changeData)) {
				// console.log("修改数据了");
				// 组合最新的数据修改
				updateDataSource(pre => {
					return pre.map((item, i) => {
						return i === rowIndex ? changeData : item;
					});
				});
			} else {
				// console.log("数据未修改");
			}
		}
	}
	// 行编辑
	function handleSaveEditRow(e, index) {
		console.log("行事件", e, index);
		console.log("RefOriginalData", RefOriginalData.current);
		// 判断是否存在未保存的数据
		if (Object.keys(RefOriginalData.current).length == 0) {
			console.log("未存修改数据，直接进入编辑状态");

			RefOriginalData.current = cloneDeep(dataSource[index]);
			editRow(index);

			return;
		}
		// console.log("originalData", JSON.stringify(RefOriginalData.current));
		const lastIndex = dataSource.findIndex(e => e.isEdit);
		const updataData = cloneDeep(dataSource[lastIndex]);
		// console.log("updataData", JSON.stringify(updataData));

		// 对比两个数据是否发生变化;
		if (JSON.stringify({ ...RefOriginalData.current, isEdit: true }) != JSON.stringify(updataData) && index !== lastIndex) {
			// 数据发生变化
			handle.saveEditRow(dataSource, fetchList, {
				successFn: res => {
					if (res.success) {
						RefOriginalData.current = {};
					}
				}
			});
		} else {
			console.log("数据未发生任何修改，直接切换行编辑");
			RefOriginalData.current = cloneDeep(dataSource[index]);
			editRow(index);
		}
	}

	// 行进入编辑状态
	function editRow(index) {
		updateDataSource(pre => {
			return pre.map((item, i) => {
				return {
					...item,
					isEdit: i == index ? true : false
				};
			});
		});
	}

	// 重置匹配状态
	useEffect(() => {
		form.setFieldsValue({ matchOrNot: undefined })
	}, [tabValue]);

	useEffect(() => {
		RefDataList.current = dataSource;
	}, [dataSource]);
	return (
		<SearchCheckboxTable
			key={tableKey}
			actions={Actions}
			actionsProps={{
				searchType: tabValue,
				isSkuType,
				setTabValue,
				dataSource,
				fetchList,
				selectedRows,
				selectedKeys,
				notMatchNum,
				form,
				pagination,
				tableKey,
				columns,
				RefOriginalData,
				formData,
				...btnOperateData
			}}
			mounted={false}
			getRowProps={(record, rowIndex) => {
				return {
					onClick(e) {
						handleSaveEditRow(e, rowIndex);
					}
				};
			}}
			{...searchSimpleTableProps}
		/>
	);
};
export default React.memo(SystemGoodsPage, () => {
	return true;
});
